package cn.stylefeng.guns.sys.modular.system.controller;

import cn.hutool.core.codec.Base64;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.core.util.RsaUtil;
import cn.stylefeng.guns.sys.modular.system.service.BtyWxService;
import cn.stylefeng.guns.sys.modular.system.service.DictService;
import cn.stylefeng.guns.sys.modular.system.service.WeChatSendTempMsgService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import static cn.stylefeng.guns.sys.core.util.DownloadUtil.saveUrlAs;
import static cn.stylefeng.guns.sys.core.util.ZipUtil.unZipFiles;

@Controller
@RequestMapping("/weixin")
public class WeixinController {
    @Resource
    private DictService dictService;
    @Resource
    private BtyWxService btyWxService;
    private Logger logger = LoggerFactory.getLogger(WeixinController.class);
    @Resource
    private WeChatSendTempMsgService weChatSendTempMsgService;

    @RequestMapping(value = "")
    @ResponseBody
    public void wageMsg() {
        try {
            RestTemplate restTemplate = new RestTemplate();
            String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDwteCbSQgiIUwMZgX6Q5cGLCwH0i9Ou7bveU8JGuJcf416bVLpBZA6Hkdu47mxUETY3Bf4++yQ3khU0Il8JvtDp84AbAPEQI+qIoTF4Zm4Yytux6XLG8IYQWx1BBXNeDuuBl3d6q6cmgDz2zDX4IkF/HmAjBJuw3jCDMHwn/ZuNQIDAQAB";
            // 调用方id
            Integer productId = 1000002886;
            // 版本号
            String version = "1.0.0";
            // 业务参数封装并加密
            JSONObject obj = new JSONObject();
            obj.put("companyId", 1000002886);
            //获取消费类型的数据
            List<Integer> list = new ArrayList<Integer>();
            //获取消费类型的数据
            list.add(1);
            //获取充值类型的数据
            list.add(2);
            //获取撤销充值类型的数据
            list.add(29);
            //获取撤销消费类型的数据
            list.add(30);
            obj.put("tradeTypeIds", list);
            String time = DateUtil.getStampNow();
            String startTime = DateUtil.getYesterDayDate() + " 00:00:00";
            String endTime = DateUtil.getYesterDayDate() + " 23:59:59";
            obj.put("queryId", time);
            obj.put("startTime", startTime);
            obj.put("endTime", endTime);
            String callbackUrl = "https://rs.bantianyaozg.com";
            //base64加密
            String callbackUrls = Base64.encode(callbackUrl.getBytes());
            System.out.println();
            obj.put("callbackUrl", callbackUrls);
            String sign = RsaUtil.encryptByPublicKey(obj.toJSONString(), publicKey);
            // 参数拼接在url后面
            String url = "https://scrm.wuuxiang.com/crm7api/api/trade/biglist.do?sign=" + sign + "&" + "productId=" + productId + "&" + "version=" + version;
            System.out.println("url:" + url);
            String result = restTemplate.getForObject(url, String.class);
            System.out.println("result:" + result);
            JsonParser jp = new JsonParser();
            //将json字符串转化成json对象
            JsonObject jo = jp.parse(result).getAsJsonObject();
            String downloadUrl = jo.get("rpData").getAsJsonObject().get("url") == null ? "" : jo.get("rpData").getAsJsonObject().get("url").toString();
            String downloadUrls = "";
            if (ToolUtil.isEmpty(downloadUrl)) {
                String searchStatus;
                String queryId = jo.get("rpData").getAsJsonObject().get("queryId").toString();
                JSONObject objs = new JSONObject();
                objs.put("companyId", 1000002886);
                objs.put("queryId", queryId);
                objs.put("tradeTypeIds", list);
                objs.put("startTime", startTime);
                objs.put("endTime", endTime);
                //base64加密
                objs.put("callbackUrl", callbackUrls);
                String sign1 = RsaUtil.encryptByPublicKey(objs.toJSONString(), publicKey);
                do {
                    // 参数拼接在url后面
                    String url1 = "https://scrm.wuuxiang.com/crm7api/api/trade/biglist.do?sign=" + sign1 + "&" + "productId=" + productId + "&" + "version=" + version;
                    System.out.println("url1:" + url1);
                    String results = restTemplate.getForObject(url1, String.class);
                    JsonObject jos = jp.parse(results).getAsJsonObject();
                    searchStatus = jos.get("rpData").getAsJsonObject().get("searchStatus") == null ? "" : jos.get("rpData").getAsJsonObject().get("searchStatus").toString();
                    System.out.println("results:" + results);
                    System.out.println("searchStatus:" + searchStatus);
                    downloadUrls = jos.get("rpData").getAsJsonObject().get("url") == null ? "" : jos.get("rpData").getAsJsonObject().get("url").toString();
                } while (searchStatus.equals("0"));
            }
            System.out.println("downloadUrl:" + downloadUrls);
            downloadUrls = downloadUrls.replace("\"", "").replace("\\", "");

            String fileName = downloadUrls.substring(downloadUrls.lastIndexOf("/"));     //为下载的文件命名
            String filePath = "D:/hyksj";      //保存目录
            int lastIndexof = downloadUrls.lastIndexOf("/");
            String fileNames = downloadUrls.substring(lastIndexof + 1);
            System.out.println("fileName:" + fileNames);
            String newFileName = URLEncoder.encode(fileNames, "utf-8");
            String subUrl = downloadUrls.substring(0, lastIndexof + 1);
            String newUrl = subUrl + newFileName;
            System.out.println("downloadUrls222:" + newUrl);
            File file = saveUrlAs(newUrl, filePath + fileName, "GET");
            System.out.println("file:" + file);
            //解压文件
            File zipFile = new File("D:\\hyksj\\" + fileName + "\\" + newFileName + "");
            String path = "D:/hyksj" + fileName + "/";
            System.out.println("path:" + path);
            String outPath = unZipFiles(zipFile, path);
            if (outPath.contains("zip")) {
                try {
                    unZipFiles(outPath, path);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            logger.info("====测试会员卡实际数据解压完成");
        } catch (Exception e) {
            logger.info("====测试会员卡实际数据出现异常===="+e.getMessage());
            e.printStackTrace();
        }
    }
//    public Object sendMsg() {
//        RestTemplate restTemplate = new RestTemplate();
//        Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("code", "access_token"));
//        String accessToken = "";
//        if (ToolUtil.isNotEmpty(dict)) {
//            accessToken = dict.getName();
//        }
//        //通过openid给指定用户发送消息
//        String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+accessToken;
//        String s="";
//        //财务部27 人事部1268783244079915009  技术部25
//       //List<BtyWx> wxList=btyWxService.list(new QueryWrapper<BtyWx>().in("openid",new Object[]{"oM18PwW_aRtOaOH0F-YwsmMxT2sM"}));
//       //List<BtyWx> wxList=btyWxService.list(new QueryWrapper<BtyWx>().in("openid",new Object[]{"oM18PwQBM_f-4xlF7DKwnLQZ7XXc"}));
//       List<BtyWx> wxList=btyWxService.list(new QueryWrapper<BtyWx>().in("openid",new Object[]{"oM18PwWDuSXALBEu7Y_YmdO8-tVw"}));
////       List<BtyWx> wxList=btyWxService.list(new QueryWrapper<BtyWx>(). notIn("dept_id",new Object[]{"25"}));
//       //List<BtyWx> wxList=btyWxService.list(new QueryWrapper<BtyWx>());
//        for (int i = 0; i <wxList.size() ; i++) {
//           String toUser=wxList.get(i).getOpenid();
//            String msgType = MessageType.TEXT_MESSAGE;
//            JSONObject contentJson = new JSONObject();
//            String name=wxList.get(i).getName()==null?"":wxList.get(i).getName();
//            String content="周末转瞬到眼前，发个祝福送祝愿：愿你休闲娱乐心情欢，亲\n" +
//                    "友聚会喜开颜，周末轻松乐满满，下周工作更顺意，工资奖金成倍\n" +
//                    "番。预祝你周末愉快！附赠早安，"+name+"同学，也许你会愿意和我聊聊天？";
//            contentJson.put("content",content);
//
//            JSONObject json = new JSONObject();
//            json.put("touser", toUser);
//            json.put("msgtype", msgType);
//            json.put("text", contentJson);
//            HttpHeaders headers = new HttpHeaders();
//            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
//            headers.setContentType(type);
//            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
//            HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
//
//            s= restTemplate.postForEntity(url,formEntity,String.class).getBody();
//            s=toUser+s;
//            logger.info("===openid==="+s);
//            return s;
//        }
//        //String touser ="oM18PwW_aRtOaOH0F-YwsmMxT2sM";
//        //String touser ="oM18PwQBM_f-4xlF7DKwnLQZ7XXc";
//        //String touser ="oM18PwWQsdIP3QEKcWejL1tF3X8s";
//        //消息类型
////        String msgType = MessageType.TEXT_MESSAGE;
////        JSONObject contentJson = new JSONObject();
////        String content="天才,加油!!!";
////        contentJson.put("content",content);
////
////        JSONObject json = new JSONObject();
////        json.put("touser", touser);
////        json.put("msgtype", msgType);
////        json.put("text", contentJson);
////        HttpHeaders headers = new HttpHeaders();
////        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
////        headers.setContentType(type);
////        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
////        HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
////        String s= restTemplate.postForEntity(url,formEntity,String.class).getBody();
//       return null;
//
//    }
}
